<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\base;

use Closure;
use Exception;
use think\exception\HttpException;

class BaseInvokeMiddleware
{
    /**
     * 调用反射执行callable支持依赖注入
     */
    public function handle($request, Closure $next)
    {
        try {
            $root = request()->root();
            $appName = str_replace("/", '', $root);
            $controller = str_replace('.', '\\', $request->controller());
            $controller = "\\app\\{$appName}\\controller\\" . $controller;
            $controllerClass = invoke($controller);
            if (($controllerClass instanceof BaseController) === false) exception($controller);
        } catch (Exception $e) {
            throw new HttpException(404, 'controller not exists:' . $e->getMessage());
        }

        $request->invokeController = $controllerClass;

        return $next($request);
    }
}